import time
import numpy as np
import pymysql 
from sklearn.preprocessing import MinMaxScaler
from joblib import dump
import requests
import pandas as pd
from datetime import datetime
import os 

class WeatherUtils(object):
    """
        天气类
    """
    def __init__(self):
        self.date_list = [
            '2024-07-01',
            '2024-08-01',
            '2024-09-01', 
            '2024-11-01',
            '2024-12-01'
        ]
        self.url="http://v1.yiketianqi.com/api"

    def get_data(self):
        """
        获取天气数据
        """
        # 先创建目录
        if not os.path.exists('regression3'): 
            os.makedirs('regression3')
        
        date_list = []
        for d in self.date_list:
            conf = {
                'appid':"29852182 ",
                'appsecret':"fUb20xDY ",
                'version':"history",
                'year':d[:4],
                'month':d[5:7],
                'city':"南昌"
            }
        
            res = requests.get(self.url,params=conf)
            res_data = res.json()
            for i in res_data['data']:
                date_list.append({
                    'date': datetime.strptime(i['ymd'], '%Y-%m-%d'),
                    'bWendu':i['bWendu'],
                    'yWendu':i['yWendu'],
                    'tianqi':i['tianqi'],
                    'fengxiang':i['fengxiang'],
                    'fengli':i['fengli']
                })

        df = pd.DataFrame(date_list)
        df.to_csv('regression3/weather_data.csv',index=False)
        return df  # 返回天气数据的DataFrame


class MysqlUtils(object):

    def __init__(self) -> None:
        self.conn = pymysql.connect(
            host= '127.0.0.1',
            user= 'text',
            password= 'root',
            database= 'lost',
            port= 3306,          # 明确指定端口
            charset= 'utf8mb4'   # 添加字符集设置
        )
        # 加载天气数据
        wu = WeatherUtils()
        self.weather_df = wu.get_data()  # 赋值天气数据到self.weather_df
        
    def is_holiday(self, date):
        """是否节假日判断
        """
        if date in ['2024-09-03', '2024-10-01', '2024-10-02', '2024-10-03', '2024-10-04', '2024-10-05', '2024-10-06', '2024-10-07', '2025-01-01', '2025-01-02', '2025-01-03']:
            return 1
        return 0
        
    def get_data(self):
        cursor = self.conn.cursor(cursor=pymysql.cursors.DictCursor)
        sql = """
        SELECT DATE(g.create_time) as date, count(*) as count
        FROM order_user_gate_rel g WHERE g.create_time BETWEEN '2024-07-01' and '2025-01-01' GROUP BY date
        """
        cursor.execute(sql)
        ret = cursor.fetchall()
        df = pd.DataFrame(ret)

        # 合并天气数据
        self.weather_df['date'] = pd.to_datetime(self.weather_df['date'])
        df['date'] = pd.to_datetime(df['date'])
        df_pivot = pd.merge(df, self.weather_df, on='date')
        df_pivot.set_index('date', inplace=True)
        df_pivot['dow'] = df_pivot.index.dayofweek  # 星期几(0-6)
        df_pivot['month'] = df_pivot.index.month  # 月份
        df_pivot['is_holiday'] = df_pivot.index.map(self.is_holiday)

        # 对星期几和月份、天气和风力、风向进行独热编码
        df_pivot = pd.get_dummies(df_pivot, columns=['dow', 'month', 'tianqi', 'fengli', 'fengxiang'], dtype=int)

        # 对温度进行类型转换（注意这里的字段名要和天气数据中的一致，比如bWendu和yWendu）
        df_pivot['bWendu'] = df_pivot['bWendu'].str.replace('°', '').astype(int)
        df_pivot['yWendu'] = df_pivot['yWendu'].str.replace('°', '').astype(int)

        # 归一化人数
        scaler = MinMaxScaler()
        feature = df_pivot[['count']]
        df_pivot['count'] = scaler.fit_transform(feature)
        dump(scaler, 'regression3/scaler.joblib')

        # 归一化天气
        weather_features = ['bWendu', 'yWendu']  # 注意字段名要和天气数据中的一致
        df_pivot[weather_features] = scaler.fit_transform(df_pivot[weather_features])
        dump(scaler, 'regression3/weather_scaler.joblib')

        df_pivot.to_csv('regression3/scenic_data.csv', index=False)

if __name__ == '__main__':
    wu = WeatherUtils()
    wu.get_data()
    mu = MysqlUtils()
    mu.get_data()
